package cn.q3c.web.tool.dao;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.stereotype.Service;

import com.googlecode.ehcache.annotations.Cacheable;

import cn.q3c.web.tool.object.Image;

@Service
public class ImageDAO extends BaseDAO{

	@Cacheable(cacheName="departCache") 
	public Image getImage(String url) throws SQLException {

		Connection conn = dataSource.getConnection();

		String sql = "select * from t_images where url=?";
		
		Image result = null;
		try {

			Object[] objs = new Object[] { url };

			result = (Image) this.query(conn, sql,
					new BeanHandler<Image>(Image.class), objs);

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(conn);
		}

		return result;
	}

	public long addImage(Image image) throws SQLException {

		Connection conn = null;

		long id = -1;
		String sql = "insert into t_images(`url`,`localfile`,`length`,`width`,`cdate`,`udate`) values(?,?,?,?,now(),now())";

		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { 
					image.getUrl(),
					image.getLocalfile(),
					image.getLength(),
					image.getWidth()};
			this.update(conn, sql, objs);

			id = getLastInsertID(conn);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}

		return id;
	}
	
	
	
	public void updateImageDate(int nid) throws SQLException {

		Connection conn = null;
		String sql = "update t_images set udate=now() where nid=?";

		try {

			conn = dataSource.getConnection();

			Object[] objs = new Object[] { 
					nid};
			this.update(conn, sql, objs);

			DbUtils.close(conn);
		} catch (SQLException e) {
			DbUtils.close(conn);
			e.printStackTrace();
		}
	}
}
